package com.ophiux.wechat.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.security.KeyStore;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;




/**
 * 通用工具类
 * @author chenh
 *2016-11-15
 */
public class CommonUtil {

	/**
	 * HTTPS请求方式
	 */
	public static String HTTP_POST = "POST";
	public static String HTTP_GET = "GET";
	
	
	/**
	 * 获取随机字符串
	 * @return
	 */
	public static String getNonceStr() {
		// 随机数
		String currTime = TenpayUtil.getCurrTime();
		// 8位日期
		String strTime = currTime.substring(8, currTime.length());
		// 四位随机数
		String strRandom = TenpayUtil.buildRandom(4) + "";
		// 10位序列号,可以自行调整。
		return strTime + strRandom;
	}
	
	public static String getTimeStamp() {
		return String.valueOf(System.currentTimeMillis() / 1000);
	}

	/**
	 * 元转换成分
	 * @param money
	 * @return
	 */
	public static String getMoney(String amount) {
		if(amount==null){
			return "";
		}
		// 金额转化为分为单位
		String currency =  amount.replaceAll("\\$|\\￥|\\,", "");  //处理包含, ￥ 或者$的金额  
        int index = currency.indexOf(".");  
        int length = currency.length();  
        Long amLong = 0l;  
        if(index == -1){  
            amLong = Long.valueOf(currency+"00");  
        }else if(length - index >= 3){  
            amLong = Long.valueOf((currency.substring(0, index+3)).replace(".", ""));  
        }else if(length - index == 2){  
            amLong = Long.valueOf((currency.substring(0, index+2)).replace(".", "")+0);  
        }else{  
            amLong = Long.valueOf((currency.substring(0, index+1)).replace(".", "")+"00");  
        }  
        return amLong.toString(); 
	}
	
	
	//HTTPS
		public static String httpsRequest(String requestUrl,String requestMethod,String outputStr){
		
			StringBuffer buffer = null;
			try {
			
				SSLContext sslContetx = SSLContext.getInstance("SSL","SunJSSE");
				
				TrustManager tm[] = new TrustManager[]{new MyX509TrustManager()};
				sslContetx.init(null,tm, new java.security.SecureRandom());
				
				SSLSocketFactory ssf = sslContetx.getSocketFactory();
				
				URL url = new URL(requestUrl);
				
				HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
				conn.setRequestMethod(requestMethod);
				conn.setSSLSocketFactory(ssf);
				conn.setDoInput(true);
				conn.setDoOutput(true);
				conn.connect();
				
				//想服务器发生请求参数
				if(outputStr != null){
					OutputStream os = conn.getOutputStream();
					os.write(outputStr.getBytes("utf-8"));
					os.close();
				}
				
				InputStream is = conn.getInputStream();
				InputStreamReader isr = new InputStreamReader(is,"UTF-8");
				BufferedReader br = new BufferedReader(isr);
				
			    buffer = new StringBuffer(); 
				String line = null;
				
				while((line = br.readLine())!=null){
					buffer.append(line);
				}
				
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			System.out.println(buffer.toString());
			return buffer.toString();
		}
	
		
		/**E:/Wechat_Cert/Wechat_CM/apiclient_cert.p12
		 * 模拟浏览器postSSL提交,微信退款HTTPS请求
		 * @param url    HTTPS地址
		 * @param xmlParam   请求参数
		 * @param sslFilePath  退款SSL安装地址 
		 * @param mch_id    退款商户号
		 * @return
		 * POST请求
		 */
		public static String getPostMethodSSL(String url,String xmlParam,String sslFilePath,String mch_id) throws Exception{
			    KeyStore keyStore  = KeyStore.getInstance("PKCS12");
		        FileInputStream instream = new FileInputStream(new File(sslFilePath));
		        String jsonStr="";
		        CloseableHttpResponse response=null;
		        try {
		            keyStore.load(instream, mch_id.toCharArray());
		        } finally {
		            instream.close();
		        }
		        SSLContext sslcontext = SSLContexts.custom()
		                .loadKeyMaterial(keyStore, mch_id.toCharArray())
		                .build();
		        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
		                sslcontext,
		                new String[] { "TLSv1" },
		                null,
		                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
		        CloseableHttpClient httpclient = HttpClients.custom()
		                .setSSLSocketFactory(sslsf)
		                .build();
		        try {
		        	HttpPost httpost = new HttpPost(url); // 退款url
		            System.out.println("executing request" + httpost.getRequestLine());
		            try {
		    	        httpost.addHeader("Connection", "keep-alive");
		    	        httpost.addHeader("Accept", "*/*");
		    	        httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
		    	        httpost.addHeader("Host", "api.mch.weixin.qq.com");
		    	        httpost.addHeader("X-Requested-With", "XMLHttpRequest");
		    	        httpost.addHeader("Cache-Control", "max-age=0");
		    	        httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
		    	        httpost.setEntity(new StringEntity(xmlParam, "UTF-8"));
		    	        response = httpclient.execute(httpost);
		    	        HttpEntity entity = response.getEntity();
		    	        jsonStr = EntityUtils .toString(response.getEntity(), "UTF-8");
		    	        EntityUtils.consume(entity);
		            } finally {
		                response.close();
		            }
		        } finally {
		            httpclient.close();
		        }
			return jsonStr;
		}
	
}
